<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */

namespace app\api\controller\android\v11;


use think\Cache;
use think\Controller;
use app\api\model\Authority;
use  app\api\model\OrderModel;
use think\Request;
use think\Db;

class Region extends Controller
{
    protected $model;
    protected $us;

    public function _initialize()
    {
        $this->model = new Authority();
        $this->us    = $this->model->check(1);
    }

    public function region_store()
    {
        $region   = db('region')->where('user_id', $this->us['user_id'])->column('store_id');
        $region[] = $this->us['store_id'];
        $data     = db('store')->whereIn('store_id', $region)->field('store_name,store_id')->select();
        r_date($data, 200);
    }

    public function time_type()
    {
        $data = [
            [
                'name' => '全部',
                'type' => 0,
            ],
            [
                'name' => '录入时间',
                'type' => 2,
            ],
            [
                'name' => '签约时间',
                'type' => 1,
            ],
        ];
        r_date($data, 200);
    }

    /*
     * 储备店长
     */
    public function reserve()
    {
        $region   = db('region')->where('user_id', $this->us['user_id'])->column('store_id');
        $region[] = $this->us['store_id'];
        $list     = db('user')
            ->where(['ce' => 1])
            ->whereIn('store_id', $region)
            ->field('user_id,store_id,username')
            ->select();
        r_date($list, 200);
    }

    public function order_state()
    {

        $data = [
            [
                'name' => '全部',
                'type' => 0,
            ],
            [
                'name' => '待接单',
                'type' => 1,
            ],

            [
                'name' => '待处理',
                'type' => 11,
            ],
            [
                'name' => '施工中',
                'type' => 4,
            ],
            [
                'name' => '已完工',
                'type' => 6,
            ],
            [
                'name' => '已完成',
                'type' => 7,
            ],
            [
                'name' => '被投诉',
                'type' => 13,
            ],

        ];
        r_date($data, 200);
    }

    public function order_channel()
    {

        $data = db('chanel')->where('type', 1)->field('title,id')->select();
        r_date($data, 200);
    }

    public function order_search()
    {

        $data = [
            [
                'name' => '全部',
                'type' => 0,
            ],
            [
                'name' => '客户姓名',
                'type' => 1,
            ],

            [
                'name' => '客户电话',
                'type' => 2,
            ],
            [
                'name' => '订单ID',
                'type' => 3,
            ],
            [
                'name' => '订单编号',
                'type' => 4,
            ],
            [
                'name' => '客户地址',
                'type' => 5,
            ],
        ];
        r_date($data, 200);
    }

    //首页数据
    public function index(OrderModel $orderModel)
    {
        $param     = Request::instance()->post();
        $condition = [];
        //排除测试数据
        $condition['us.ce'] = 1;
        //时间区间
        if (!empty($param['order_startDate']) && !empty($param['order_endDate'])) {
            $start = strtotime($param['order_startDate'] . ' 00:00:00');
            $end   = strtotime($param['order_endDate'] . ' 23:59:59');
            if (intval($param['order_timeType']) == 1) {

                $condition['a.state']     = ['between',[4,9]];
                $condition['co.con_time'] = ['between', [$start, $end]];

            } else {
                $condition['a.created_time'] = ['between', [$start, $end]];
            }
        }

        //订单状态
        if (!empty($param['order_start'])) {
            switch (intval($param['order_start'])) {
                case 1://待接单
                    $condition['a.state']        = 1;
                    $condition['a.undetermined'] = 0;
                    break;
                case 4://施工中
                    $condition['a.state'] = [['eq', 4], ['eq', 5], 'or'];
                    break;
                case 6://已完工
                    $condition['a.state']       = 7;
                    $condition['pr.product_id'] = Db::raw("is null");
                    break;
                case 7://已完成
                    $condition['a.state'] = 7;

                    $condition['pr.product_id'] = Db::raw("is NOT  null");
                    break;
                case 11://待处理
                    //$condition['order.state']=1;
                    $condition['a.undetermined'] = 1;
                    break;
                case 12://待指派
                    $condition['a.state'] = 0;
                    break;
                case 13://被投诉
                    $condition['complaint.order_id'] = 'is not null';
                    break;
                default:
//                    $condition[] = ['order.state', '=', intval($param['order_start'])];
//                    break;
            }

        }
        //订单来源
        if (!empty($param['order_chanel'])) {
            $condition['a.channel_id'] = ['=', intval($param['order_chanel'])];
        }
        //所属城市
        if (!empty($param['order_city'])) {
            $condition['a.city_id'] = ['=', intval($param['order_city'])];
        }
        //权限和分店搜索
        $user = db('user')
            ->where(['status' => 0]);
        if (!empty($param['order_store'])) {
            $user->where('store_id', $param['order_store']);
        } else {
            $region   = db('region')->where('user_id', $this->us['user_id'])->column('store_id');
            $region[] = $this->us['store_id'];
            $user->whereIn('store_id', $region);
        };


        //所属店长
        if (!empty($param['order_user'])) {
            $condition['a.assignor'] = ['=', $param['order_user']];
        } else {
            $list                    = $user->column('user_id');
            $condition['a.assignor'] = ['in', $list];
        }
        //跟进状态
        if (isset($param['order_follow'])) {
            $follow      = [
                1 => '未上门',
                2 => '跟进中',
                3 => '签约',
                4 => '飞单',
                5 => '售后',
                6 => '投诉',
            ];
            $condition[] = ['through.status', '=', $follow[intval($param['order_follow'])]];
        }

        //搜索
        if (!empty($param['order_search']) && !empty($param['keywords'])) {
            switch (intval($param['order_search'])) {
                case 1:
                    $condition['a.contacts'] = ['like', '%' . $param['keywords'] . '%'];
                    break;
                case 2:
                    $condition['a.telephone'] = ['like', '%' . $param['keywords'] . '%'];
                    break;
                case 3:
                    $condition['a.order_id'] = ['=', $param['keywords']];
                    break;
                case 4:
                    $condition['a.order_no'] = ['like', '%' . $param['keywords'] . '%'];
                    break;
                case 5:
                    $condition['a.addres'] = ['like', '%' . $param['keywords'] . '%'];
                    break;
                case 6:
                    $condition['a.username'] = ['like', '%' . $param['keywords'] . '%'];
                    break;
                default:
                    # code...
                    break;
            }
        }
        $m = $orderModel->table('order')
            ->alias('a')
            ->field('a.order_id,a.order_no,a.addres,a.contacts,a.telephone,a.remarks,a.created_time,a.state,a.planned,b.title,p.province,c.city,u.county,go.title,co.con_time,st.xiu_id,me.time as message_time,us.username as shopowner_username,us.user_id,a.planned')
            ->join('chanel b', 'a.channel_id=b.id', 'left')
            ->join('province p', 'a.province_id=p.province_id', 'left')
            ->join('city c', 'a.city_id=c.city_id', 'left')
            ->join('county u', 'a.county_id=u.county_id', 'left')
            ->join('user us', 'a.assignor=us.user_id', 'left')
            ->join('goods_category go', 'a.pro_id=go.id', 'left')
            ->join('contract co', 'a.contract_id=co.contract_id', 'left')
            ->join('startup st', 'a.startup_id=st.startup_id', 'left')
            ->join('before be', 'a.before_id=be.before_id', 'left')
            ->join('message me', 'a.order_id=me.order_id and me.type=6 and a.assignor=me.user_id', 'left')
            ->join('cost cos', 'a.order_id=cos.order_id ', 'left')
            ->join('product pr', 'a.order_id=pr.orders_id ', 'left')
            ->join('complaint complaint', 'a.order_id=complaint.order_id ', 'left')
            ->join('order_rework rework', 'a.order_id=rework.order_id ', 'left');

        $list = $m->where($condition)->page($param['page'], $param['limit'])->order('me.time desc')->select();
        if (is_array($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['created_time'] = date('Y-m-d H:i', $value['created_time']);
                $list[$key]['message_time'] = date('Y-m-d H:i', $value['message_time']);
                $list[$key]['con_time']     = !empty($value['con_time']) ? date('Y-m-d H:i', $value['con_time']) : '';
                $list[$key]['planned']      = !empty($value['planned']) ? date('Y-m-d H:i', $value['planned']) : '';
                $shi['ids']                 = $value['xiu_id'];
                if (!empty($shi['ids'])) {
                    $results = send_post(UIP_SRC . "/support-v1/user/old-list", $shi);
                    $results = json_decode($results, true);
                    if ($results['code'] == 200) {
                        $list[$key]['master'] = object_array($results['data']);
                    } else {
                        $list[$key]['master'] = null;
                    }
                } else {
                    $list[$key]['master'] = null;
                }
                $value['states'] = $orderModel::type($value['state']);
            }
        }
        r_date($list, 200);
    }


}